package com.tacademy.android.lbs.friend;

import java.io.StringReader;

import org.restlet.data.CharacterSet;
import org.restlet.data.Form;
import org.restlet.data.Language;
import org.restlet.data.MediaType;
import org.restlet.data.Status;

import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;

import com.google.gson.Gson;
import com.tacademy.android.lbs.friend.model.UserLocation;
import com.tacademy.android.lbs.friend.model.UserLocationOutput;

public class MyLocationRestlet extends ServerResource {
	FriendDAO friendDAO = new FriendDAO();
	Gson gson = new Gson();

	@Post
	public Representation post(Representation representation) {
		Form form = new Form(representation);
		String userLocationData = form.getFirstValue("data"); //URLDecoder.decode
		Representation rep = null;
		try {
			UserLocation userLocation = gson.fromJson(new StringReader(userLocationData), UserLocation.class);
			if (userLocation != null) {
				friendDAO.saveUser(userLocation);
			}
			getResponse().setStatus(Status.SUCCESS_CREATED);
			rep = new StringRepresentation(gson.toJson(new UserLocationOutput(userLocation)), MediaType.TEXT_PLAIN, Language.ALL, CharacterSet.UTF_8);
			// rep.setIdentifier(getRequest().getResourceRef().getIdentifier() + userLocation.getKey());
		} catch (Throwable thr) {
			getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
			rep = new StringRepresentation("there was an error creating Location", MediaType.TEXT_PLAIN, Language.ALL, CharacterSet.UTF_8);
		}
		return rep;
	}
}
